#! /usr/bin/env bash

set -ue
# whether the parameter of [gcc -o] exists
output=0

#determine whether the parameter -o exists
exists_o_opt(){
    local i=0;
    
    for p; do
        ((++i))
        if [ "$p" == "-o" ]; then
            break;
        fi
    done

    if [ "$i" != "$#" ]; then
        output=1
    fi
}

help(){
    local code=${1:-0};
    echo >&2 "Usage: ./compiler.h [source] [-o]...";
    exit $code
}
    
get_project_root(){
    local sh=$1;

    # parse soft link
    if [ -L $1 ]; then
        root="$(dirname "$(readlink -f "$1")")"/

    elif [ -L $1 ]; then
        root="$(dirname "$(realpath $BASH_SOURCE[0])")"/;
    fi
}


exists_o_opt "$@"

#root path
#root="$(dirname "$(realpath $BASH_SOURCE[0])")"/;
root=
get_project_root $0

#bin path
binpath=${root}bin/

#file relative filename
filename=$1

if [ -z "$1" ]; then
    help 1;
fi

#file is absolute path
if [ "${1:0:1}" == "/" ]; then
    filename=${1#$root}

# omit './' on start
elif [ "${1:0:2}" == "./" ]; then
    filename=${1:2};
fi

shift

sourcename=${root}$filename

destname=${binpath}$filename


if [ ! -e "${sourcename}" ]; then
    help 1;
fi

if [ $output -eq 0 ]; then
    destname=${destname%.*}
    set --  "-o $destname" $@
fi

set -- "${sourcename}" $@
 
gcc $@

echo "complile complete!"
